/**
 * 
 */
package com.rocky.project.action.model;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;

import com.opensymphony.webwork.ServletActionContext;
import com.rocky.project.action.base.BaseAction;
import com.rocky.project.model.admin.ArchivingConfig;
import com.rocky.project.model.admin.Area;
import com.rocky.project.model.family.Archive;
import com.rocky.project.model.family.Family;
import com.rocky.project.model.family.Person;
import com.rocky.project.util.BeanUtil;
import com.rocky.project.util.JSONUtil;
import com.rocky.project.util.WebUtil;

/**
 * @author rocky.shen
 *
 */
public class ArchivingConfigAction extends BaseAction {
	private static final long serialVersionUID = 1L;

	private ArchivingConfig archivingConfig;

	public ArchivingConfig getArchivingConfig() {
		return archivingConfig;
	}

	public void setArchivingConfig(ArchivingConfig archivingConfig) {
		this.archivingConfig = archivingConfig;
	}

	public String doarchiving() throws Exception {
		String systemEnable = WebUtil.getConfigValue("project.systemEnable");	
		if(systemEnable.equals("true")){
			WebUtil.setConfigValue("project.systemEnable", "false");
		}
	
		String areaid = WebUtil.getParaValue("areaid");
		String isEnded = WebUtil.getParaValue("isEnded");

		Area area = (Area) baseService.get(Area.class, Long.valueOf(areaid));
		List<Long> areaids = new ArrayList<Long>();
		getIdsFromParentarea(area, areaids);
		Date snapTime = Calendar.getInstance().getTime();
		//		List<Object> paramsvalues = new LinkedList<Object>();
		StringBuffer str = new StringBuffer(areaids.toString());
		str.replace(0, 1, "");
		str.replace(str.length() - 1, str.length(), "");
		//and m.latest=true and m.snapTime is null
		String queryHql = "SELECT m FROM Archive AS m WHERE m.deleted = false  and m.family.area.id in (" + str.toString() + ")  ";
		this.pageRecords = baseService.executeHqlNoParam(queryHql, 0, null);
		for (Iterator iter = this.pageRecords.iterator(); iter.hasNext();) {
			Archive archive = (Archive) iter.next();
			archive.setLatest(false);
			archive.setSnapTime(snapTime);
			baseService.update(archive);

			Archive archiveNew = new Archive();
			BeanUtil.copyProperties(archive, archiveNew, BeanUtil.DEFAULT_EXCLUDES);
			//			archiveNew.setId(-1L);
			//			archiveNew.setLatest(true);
			//			archiveNew.setSnapTime(null);
			//			Family family;	
			//			Set photos;//照片
			//			Set pics;//图纸
			//			Set archivePics;//历史档案
			//			Set files;//备注文档		
			baseService.evict(archive);
			//			archiveNew.setFamily(archive.getFamily());
			//			archiveNew.setPhotos(archive.getPhotos());
			//			archiveNew.setPics(archive.getPics());
			//			archiveNew.setArchivePics(archive.getArchivePics());			
			//			archiveNew.setFiles(archive.getFiles());
			Family family = new Family();
			BeanUtil.copyProperties(archive.getFamily(), family);
			List<String> jsonlist = new ArrayList<String>();
			Set set = archive.getFamily().getPersons();
			for (Iterator iterator = set.iterator(); iterator.hasNext();) {
				Person person = (Person) iterator.next();
				jsonlist.add("{id:'" + person.getId() + "',name:'" + person.getName() + "'}");
			}
			family.setPersonsJson(jsonlist.toString());
			String familyJson = JSONUtil.bean2Json(family, new String[] {"isDeleted","callback","archives","area","householder","persons","userRoleR","deleted","description","keyword","modifyTime","password","showindex","status","type","username" }, JSONUtil.DEFAULT_DATEPATTERN).toString();
			log.info("#familyJson#:" + familyJson);
			archiveNew.setFamilyJson(familyJson);//TODO			
			baseService.create(archiveNew);
		}
		area.setSnapTime(snapTime);
		baseService.update(area);
		log.info("ArchiveAction:doarchiving.action");
		systemEnable = WebUtil.getConfigValue("project.systemEnable");	
		if(systemEnable.equals("false")){
			WebUtil.setConfigValue("project.systemEnable", "true");
//			WebUtil.saveConfig();
		}	
		if(isEnded!=null && isEnded.equals("true")){
			String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
			this.pageRecords = baseService.executeHqlNoParam("SELECT m FROM ArchivingConfig AS m WHERE m.year = '"+year+"'  ",  0, null);
			archivingConfig = (ArchivingConfig) this.pageRecords.iterator().next();
			archivingConfig.setRealTime(Calendar.getInstance().getTime());
			baseService.update(archivingConfig);
		}		
		return ajaxResult;
	}

	private void getIdsFromParentarea(Area area, List<Long> areaids) {
		areaids.add(area.getId());
		Set children = area.getChildren();
		for (Iterator iterator = children.iterator(); iterator.hasNext();) {
			Area area2 = (Area) iterator.next();
			getIdsFromParentarea(area2, areaids);
		}
	}

	public String canarchiving() throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> data = new HashMap<String, Object>();
		Date today = Calendar.getInstance().getTime();
		data.put("today", sdf.format(today));
		String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
		data.put("year", year);
		this.pageRecords = baseService.executeHqlWithParam("SELECT m FROM ArchivingConfig AS m WHERE m.year = ?  ", new Object[] { year }, 0, null);
		if (this.pageRecords == null || this.pageRecords.isEmpty()) {
			data.put("msg", "没有设置归档时间，目前不能进行归档操作！");
			data.put("enabled", "false");
		} else {
			archivingConfig = (ArchivingConfig) this.pageRecords.iterator().next();
			Date startTime = archivingConfig.getStartTime();
			Date endTime = archivingConfig.getEndTime();
			if (today.after(startTime) && today.before(endTime)) {
				data.put("msg", "请及时进行归档操作！");
				data.put("enabled", "true");
			} else {
				data.put("msg", "目前不在设置的归档时间内，不能进行归档操作！");
				data.put("enabled", "false");
			}

			data.put("startTime", sdf.format(startTime));
			data.put("endTime", sdf.format(endTime));
		}
		this.ajaxResultMap.put("data", data);
		log.info("canarchiving");
		return ajaxResult;
	}

	@Override
	public String read() throws Exception {
		java.util.List<Object> paramsvalues = new LinkedList<Object>();
		String queryHql = "SELECT m FROM ArchivingConfig AS m WHERE m.deleted = false   ";
		String keywordFilterValue = WebUtil.getParaValue("keywordFilterValue");
		String id = WebUtil.getParaValue("id");
		if (keywordFilterValue != null && !keywordFilterValue.equals("")) {
			queryHql += "    and (m.keyword like ? or m.cardnumber like ?  ) ";
			paramsvalues.add("%" + keywordFilterValue + "%");
			paramsvalues.add("%" + keywordFilterValue + "%");
		}
		if (id != null && !id.equals("")) {
			queryHql += "    and m.id = ?   ";
			paramsvalues.add(Long.valueOf(id));
		}
		queryHql = queryHql + "    order by m.id desc";
		this.pageRecords = baseService.executeHqlWithParam(queryHql, paramsvalues.toArray(), getStart(), getPageSize());
		this.rowCount = baseService.getCountHqlWithParam(queryHql, paramsvalues.toArray());

		this.ajaxResultMap.put("data", this.pageRecords);
		this.ajaxResultMap.put("rowCount", this.rowCount);

		log.info("ArchivingConfigAction:read.action->" + this.rowCount);
		//		return ajaxResult;
		return "archivingconfigread";
	}

	@Override
	public String readOne() throws Exception {
		archivingConfig = (ArchivingConfig) baseService.get(ArchivingConfig.class, Long.valueOf(id));
		return super.readOne();
	}

	@Override
	public String createProcess() throws Exception {
		JSONObject obj = JSONObject.fromObject(this.jsondata);
		archivingConfig = (ArchivingConfig) JSONObject.toBean(obj, ArchivingConfig.class);
		String year = archivingConfig.getYear();
		this.pageRecords = baseService.executeHqlWithParam("SELECT m FROM ArchivingConfig AS m WHERE m.year = ?  ", new Object[] { year }, 0, null);
		if (this.pageRecords != null && !this.pageRecords.isEmpty()) {
			this.addActionMessage("一年只能设置一个归档时间段");
			return ERROR;
		}
		WebUtil.init4create(archivingConfig);
		baseService.create(archivingConfig);
		return ajaxResult;
	}

	@Override
	public String updateProcess() throws Exception {
		JSONObject obj = JSONObject.fromObject(this.jsondata);
		archivingConfig = (ArchivingConfig) JSONObject.toBean(obj, ArchivingConfig.class);
		String year = archivingConfig.getYear();
		this.pageRecords = baseService.executeHqlWithParam("SELECT m FROM ArchivingConfig AS m WHERE m.year = ? and m.id <> ? ", new Object[] { year, archivingConfig.getId() }, 0, null);
		if (this.pageRecords != null && !this.pageRecords.isEmpty()) {
			this.addActionMessage("一年只能设置一个归档时间段");
			return ERROR;
		}
		ArchivingConfig objDb = (ArchivingConfig) baseService.get(ArchivingConfig.class, archivingConfig.getId());
		BeanUtil.copyProperties(archivingConfig, objDb);
		WebUtil.init4modify(objDb);
		baseService.update(objDb);
		return ajaxResult;
	}

	@Override
	public String deleteProcess() throws Exception {
		String[] ids = WebUtil.getParaValue("ids").split(",");
		for (String id : ids) {
			ArchivingConfig objDb = (ArchivingConfig) baseService.get(ArchivingConfig.class, Long.valueOf(id));
			if (objDb.getRealTime() == null || objDb.getRealTime().equals("")) {
				baseService.deleteTrue(objDb);
			}
		}
		ServletActionContext.getResponse().setContentType("text/plain charset=utf-8");
		ServletActionContext.getResponse().getWriter().write("{success:true}");
		return NONE;
	}
}
